package xyz.xuminghai;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 2023/2/21 14:39 星期二<br/>
 *
 * 自定义Classloader
 *
 * @author xuMingHai
 */
public class MyClassLoader extends ClassLoader {

	public MyClassLoader() {
		super(null);
	}

	@Override
	protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
		synchronized (getClassLoadingLock(name)) {
			// First, check if the class has already been loaded
			Class<?> c = super.findLoadedClass(name);
			if (c == null) {
				if (name.startsWith("java.")) {
					return super.loadClass(name, resolve);
				}

				String classPath = name.replace('.', '/').concat(".class");
				try {
					URI uri = ClassLoader.getSystemResource(classPath).toURI();
					System.out.println("uri = " + uri);
					byte[] byteCodes = Files.readAllBytes(Paths.get(uri));
					return super.defineClass(name, byteCodes, 0, byteCodes.length);
				}
				catch (IOException | URISyntaxException e) {
					throw new ClassNotFoundException(classPath, e);
				}
			}
			return c;
		}

	}

}
